﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow)
{
	ui->setupUi(this);

    setWindowTitle(VERSION);

	mysqlClient = new mysql();
	serial = new QSerialPort(this);
	endata = new en_data();
	dedata = new de_data();

    //模组数据库表
    mysqlMzClient = new mysql();

	m_time_out_serial = new QTimer();
	m_time_out_serial_count = 0;
	m_time_out_serial->setInterval(1000);

	process_flag = STEP_MAX;
	is_first_rev_error = false;

    writelog = new QSettings("log.ini", QSettings::IniFormat);
    m_message_box = new QMessageBox();
    chrgDtctntms = 2;
    IsShow = false;

	initActionsConnections();
	serialPort_config();
	serialBaud_config();
	read_settings();

	//endata->packet_commond(AT_DEVICEINFO,"ii",2,29,1);
}

MainWindow::~MainWindow()
{
    delete writelog;
	delete ui;
}

bool MainWindow::nativeEventFilter(const QByteArray &eventType, void *message, long *)
{
	if(eventType == "windows_generic_MSG" || eventType == "windows_dispatcher_MSG")
	{
		MSG* pMsg = reinterpret_cast<MSG*>(message);
		if(pMsg->message == WM_DEVICECHANGE)
		{
			if(pMsg->wParam == DBT_DEVICEARRIVAL || pMsg->wParam == DBT_DEVICEREMOVECOMPLETE)
			{
				serialPort_config();
			}
		}
	}
	return false;
}

void MainWindow::Delay(unsigned short ms)
{
  QElapsedTimer t;

  t.start();
  while(t.elapsed()<ms)
  {
	QCoreApplication::processEvents();
  }
  return ;
}

void MainWindow::initActionsConnections()
{
	connect(serial, SIGNAL(readyRead()), this, SLOT(serialReadData()));
	connect(m_time_out_serial,SIGNAL(timeout()),this,SLOT(serial_time_out()));
}

void MainWindow::stop_process()
{
	process_flag = STEP_MAX;
	serialReceiveData.clear();
	m_time_out_serial->stop();
    m_time_out_serial_count =0 ;
    //ui->start_pushButton->setEnabled(true);
	ui->cuscode_lineEdit->setEnabled(true);
	ui->cuscode_lineEdit->clear();
	ui->cuscode_lineEdit->setFocus();
	ui->cuscode_lineEdit->selectAll();
	is_first_rev_error = false;
    chrgDtctntms = 2;
    IsShow = false;
}

void MainWindow::showresult_cusid()
{
    showresult *temp = new showresult(dedata->info->cusid);
    temp->show();
}

void MainWindow::on_actionAbout_triggered()
{
	QMessageBox::information(this, QStringLiteral("版权"), QStringLiteral("公司：北京飞图同辉科技有限公司\r\n官网：http://www.flyscale.cn\r\n版本：")+QStringLiteral(VERSION), QMessageBox::Ok);
}

void MainWindow::on_actionSetting_triggered()
{
	bool isOK;

	if(ui->IP_lineEdit->isEnabled())
	{
		ui->IP_lineEdit->setEnabled(false);
		ui->port_lineEdit->setEnabled(false);
		ui->sql_lineEdit->setEnabled(false);
		ui->table_lineEdit->setEnabled(false);
        ui->Setdigit_lineEdit->setEnabled(false);

		ui->com_comboBox->setEnabled(false);
		ui->baud_comboBox->setEnabled(false);
		ui->version_lineEdit->setEnabled(false);
        ui->mcuversion_lineEdit->setEnabled(false);
        ui->configIp_lineEdit->setEnabled(false);
        ui->checkBox->setEnabled(false);
        ui->checkBox_2->setEnabled(false);
		ui->actionSetting->setText("配置参数");
		write_settings();
		return ;
	}

	QString text = QInputDialog::getText(NULL, "管理员登陆","请输入管理员密码",QLineEdit::Password,"",&isOK);

	if(isOK)
	{
		if(text == PASSWORD)
		{
			ui->IP_lineEdit->setEnabled(true);
			ui->port_lineEdit->setEnabled(true);
			ui->sql_lineEdit->setEnabled(true);
			ui->table_lineEdit->setEnabled(true);
            ui->Setdigit_lineEdit->setEnabled(true);
			ui->com_comboBox->setEnabled(true);
			ui->baud_comboBox->setEnabled(true);
			ui->version_lineEdit->setEnabled(true);
            ui->mcuversion_lineEdit->setEnabled(true);
            ui->configIp_lineEdit->setEnabled(true);
            ui->checkBox->setEnabled(true);
            ui->checkBox_2->setEnabled(true);
			ui->actionSetting->setText("保存配置");
		}
		else
		{
			QMessageBox::information(this, tr("提示消息"), tr("输入密码错误请重试！"), QMessageBox::Ok);/**/
		}
	}
}

void MainWindow::write_settings()
{
	QSettings *writeConfig = new QSettings("Option.ini", QSettings::IniFormat);
	writeConfig->setValue("/serialPort/serial_num",ui->com_comboBox->currentText());
	writeConfig->setValue("/serialPort/BaudRate",ui->baud_comboBox->currentIndex());
	strpass pass;

	writeConfig->setValue("/mysql/IP",(pass.getXorEncryptDecrypt(ui->IP_lineEdit->text(), 11)));
	writeConfig->setValue("/mysql/IP_PN",(pass.getXorEncryptDecrypt(ui->port_lineEdit->text(), 12)));
	writeConfig->setValue("/mysql/database",(pass.getXorEncryptDecrypt(ui->sql_lineEdit->text(), 13)));
	writeConfig->setValue("/mysql/table",(pass.getXorEncryptDecrypt(ui->table_lineEdit->text(), 14)));
    writeConfig->setValue("/info/FLY900 version",(pass.getXorEncryptDecrypt(ui->version_lineEdit->text(), 15)));
    writeConfig->setValue("/info/CC2541 version",(pass.getXorEncryptDecrypt(ui->mcuversion_lineEdit->text(), 16)));
    writeConfig->setValue("/info/IP",(pass.getXorEncryptDecrypt(ui->configIp_lineEdit->text(), 15)));
    writeConfig->setValue("/info/Setdigit",(pass.getXorEncryptDecrypt(ui->Setdigit_lineEdit->text(), 2)));

    int f_checked = ui->checkBox->isChecked();
    writeConfig->setValue("/info/SlrEnrgyCnfg",f_checked);
    f_checked = ui->checkBox_2->isChecked();
    writeConfig->setValue("/info/CnfgrngIp",f_checked);

	delete writeConfig;
}

void MainWindow::serialPort_config()
{
	ui->com_comboBox->clear();
	unsigned short int index = 1;

	foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
	{
		ui->com_comboBox->insertItem(index,info.portName());
		index++;
	}
}

void MainWindow::serialBaud_config()
{
	ui->baud_comboBox->addItem(QStringLiteral("9600"), QSerialPort::Baud9600);
	ui->baud_comboBox->addItem(QStringLiteral("19200"), QSerialPort::Baud19200);
	ui->baud_comboBox->addItem(QStringLiteral("38400"), QSerialPort::Baud38400);
	ui->baud_comboBox->addItem(QStringLiteral("115200"), QSerialPort::Baud115200);
	ui->baud_comboBox->setCurrentIndex(3);
}

bool MainWindow::serialOpen()
{
	if(serial->isOpen())
	{
		//serialClose();
		QMessageBox::warning(this, QStringLiteral("警告"),
								   QStringLiteral("串口打开失败，串口已被打开。"),
								   QMessageBox::Ok) ;
		return false;
	}
	serial->setPortName(ui->com_comboBox->currentText());
	serial->setBaudRate(ui->baud_comboBox->currentText().toInt());
	serial->setDataBits(QSerialPort::Data8);
	serial->setParity(QSerialPort::NoParity);
	serial->setStopBits(QSerialPort::OneStop);
	serial->setFlowControl(QSerialPort::NoFlowControl);

	if (serial->open(QIODevice::ReadWrite))
	{
		return true;
	}
	else
	{
		QMessageBox::critical(this, tr("Error"), serial->errorString());
		serial->close();
		return false;
	}
}

bool MainWindow::serialClose()
{
	if(serial->isOpen())
	{
		serial->close();
		return true;
	}
	return false;
}

void MainWindow::parse_receive_data()
{
	QByteArray sendData;

	switch(process_flag)
	{
        case STEP_SlrChrgDtcton_ENGINEER:
        {
            m_time_out_serial->stop();
            if(ui->checkBox->isChecked())
            {
                if(2 == chrgDtctntms)
                {
                    ui->success_label->setText("太阳能充电检测中....");
                    m_message_box->information(this,"太阳能充电提示","<font size='26' color='blue'>请将设备移入卤素灯照射范围（先点击后移入）!!!</font>","确定");

                }
                if(serialReceiveData.contains("PLUG_OUT!!"))
                {
                    chrgDtctntms = 2;
                    ui->success_label->setText("检测是否通过模组测试");
                    serial->clear();
                    serialReceiveData.clear();
                    serial->write(AT_IMEI_STR);
                    m_time_out_serial->start();
                    serialReceiveData.clear();
                    ui->start_pushButton->setEnabled(false);
                    process_flag = STEP_READ_IEMI;

                    writelog->setValue("/STEP_SlrChrgDtcton_ENGINEER/r/n","pass PLUG_OUT");

                    break;
                }
                if (serialReceiveData.contains("START CHARGING!!") ||serialReceiveData.contains("CHARGE DONE!!"))
                {
//                    if(1 == chrgDtctntms)
                    {
                        m_message_box->information(this,"太阳能充电检测","<font size='26' color='blue'>充电已成功，请将设备移出卤素灯照射范围（先点击后移出）!!!</font>");
                        chrgDtctntms = -1;
                    }
                }
                else
                {
                    if(chrgDtctntms--)
                    {
                        process_flag = STEP_SlrChrgDtcton_ENGINEER;
                        break;
                    }
                    stop_process();
                    QMessageBox::warning(this, QStringLiteral("警告"),
                                               QStringLiteral("太阳能充电失败"),
                                               QMessageBox::Ok) ;
                    ui->success_label->setText("太阳能充电失败");
                }
            }
            else
            {
                ui->success_label->setText("检测是否通过模组测试");
                serial->clear();
                serialReceiveData.clear();
                serial->write(AT_IMEI_STR);
                m_time_out_serial->start();
                serialReceiveData.clear();
                ui->start_pushButton->setEnabled(false);
                process_flag = STEP_READ_IEMI;
                break;
            }

            break ;
        }
        case STEP_READ_IEMI:
        {
            //检查是否通过模组模组测试，只有通过测试的才能继续往下进行
            m_time_out_serial->stop();
            if (serialReceiveData.contains("OK") && serialReceiveData.contains("8643020317"))
            {
                QString ImeiInfo;
                ImeiInfo.append(serialReceiveData);
//                QString Imei = ImeiInfo.mid(2,15);//"864302031756385"
                int index = ImeiInfo.indexOf("\r\n8643020317");
                QString Imei = ImeiInfo.mid(index+2, 15);

                writelog->setValue("/info/ImeiInfo",Imei);
                //在模组测试数据库对应表中依据sn号进行查询
                if(!on_judgeSnsql_mysqlMzClient(Imei))
                {
                    stop_process();
                    QMessageBox::warning(this, QStringLiteral("警告"),
                                               QStringLiteral("模组测试检测失败参上"),
                                               QMessageBox::Ok) ;
                    ui->success_label->setText("模组测试检测失败参上");
                }
                else
                {
                    ui->success_label->setText("开启工程模式....");
                    serial->write("AT+TEST=23,2\r\n");
                    m_time_out_serial->start();
                }
                ui->start_pushButton->setEnabled(false);
                process_flag = STEP_READ_ENGINEER;
            }
            else
            {
                stop_process();
                QMessageBox::warning(this, QStringLiteral("警告"),
                                           QStringLiteral("SN获取失败无法检测"),
                                           QMessageBox::Ok) ;
                ui->success_label->setText("SN获取失败无法检测");
            }

            break ;
        }
        case STEP_READ_ENGINEER:
        {
            m_time_out_serial->stop();
            if (serialReceiveData.contains("ENGINEERING"))
            {
                ui->success_label->setText("读取设备版本号....");
                serialReceiveData.clear();
                serial->clear();
                sendData.append(endata->packet_commond(AT_DEVICEINFO,"ii",2,29,1));
                //click 以后读取 设备信息
                serial->write(sendData);
                m_time_out_serial->start();
                ui->start_pushButton->setEnabled(false);
                process_flag = STEP_READ_VERSION_ID;
            }
            else
            {
                stop_process();
                mysqlClient->mysqlSetusedzero(dedata->info->device_id);
                QMessageBox::warning(this, QStringLiteral("警告"),
                                           QStringLiteral("工程模式失败"),
                                           QMessageBox::Ok) ;
                ui->success_label->setText("工程模式失败");
            }
            break ;
        }
		case STEP_READ_VERSION_ID:
			{
				QString dev_version;
                QString mcu_version ;
				QString info;

				m_time_out_serial->stop();
				info.append(serialReceiveData);
                dev_version.append(dedata->gei_info(info,"FLY900 version:",":",0));
                mcu_version.append(dedata->gei_info(info,"CC2541 version:",":",0));
                dev_version = dev_version.trimmed();
                mcu_version = mcu_version.trimmed();
                qDebug()<< "dev_version = "<< dev_version ;
                qDebug()<< "mcu_version = "<< mcu_version ;
				ui->re_version_lineEdit->setText(dev_version);
                ui->mcure_version_lineEdit->setText(mcu_version);

                if(dev_version == ui->version_lineEdit->text() && mcu_version == ui->mcuversion_lineEdit->text())
				{
                    ui->success_label->setText("写入设备ID....");
                    sendData.append(endata->packet_commond(AT_SETDEVID,"is",2,1,dedata->info->device_id.toStdString().c_str()));
                    qDebug()<< "senddata" <<sendData ;
                    serial->write(sendData);
                    m_time_out_serial->start();
                    process_flag = STEP_WRITE_SIM_ID;
				}
				else
				{
                    if(ui->mcuversion_lineEdit->text()== mcu_version)
                    {
                        stop_process();
                        mysqlClient->mysqlSetusedzero(dedata->info->device_id);
                        QMessageBox::warning(this, QStringLiteral("警告"),
                                                   QStringLiteral("模块版本号不匹配"),
                                                   QMessageBox::Ok) ;
                        ui->success_label->setText("模块版本号不匹配");
                        break;
                    }
                    else
                    {
                        stop_process();
                        mysqlClient->mysqlSetusedzero(dedata->info->device_id);
                        QMessageBox::warning(this, QStringLiteral("警告"),
                                                   QStringLiteral("单片机版本号不匹配"),
                                                   QMessageBox::Ok) ;
                        ui->success_label->setText("单片机版本号不匹配");
                        break;
                    }
				}
  //              qDebug()<<"serialRecriveData 1:" <<serialReceiveData;
                serialReceiveData.clear();
  //              qDebug()<<"serialRecriveData 2:" <<serialReceiveData;
			}
            break;
        case STEP_WRITE_SIM_ID:
            {
                m_time_out_serial->stop();
                ui->success_label->setText("检测sim中");
                sendData.append((AT_SIM_STR+tr("\r\n")));
                serialReceiveData.clear();
                serial->write(sendData);
                m_time_out_serial->start();
                process_flag = STEP_READ_SIM_ID;
                break;
            }

        case STEP_READ_SIM_ID:
            {
                QString info ;
                m_time_out_serial->stop();
                ui->success_label->setText("SIM卡检测中");
                info.append(serialReceiveData);
                if (!info.contains("CCID"))
                {
                    stop_process();
                    mysqlClient->mysqlSetusedzero(dedata->info->device_id);
                    QMessageBox::warning(this, QStringLiteral("警告"),
                                               QStringLiteral("请检查SIM卡是否放入！"),
                                               QMessageBox::Ok) ;
                    ui->success_label->setText("SIM卡未插入！");
                    break ;
                }
                serialReceiveData.clear();
                sendData = "AT\r\n";
                serial->write(sendData);
                m_time_out_serial->start();
                process_flag = STEP_WRITE_DEVICE_ID ;
             }
            break ;

		case STEP_WRITE_DEVICE_ID:
			//qDebug()<<"STEP_WRITE_DEVICE_ID";
            m_time_out_serial->stop();
            serialReceiveData.clear();
            ui->success_label->setText("读取信息中....");
			sendData.append(endata->packet_commond(AT_DEVICEINFO,"ii",2,29,1));
            serial->write(sendData);
			m_time_out_serial->start();
            sendData.append(endata->packet_commond(AT_SETDEVID,"is",2,1,dedata->info->device_id.toStdString().c_str()));
            serial->write(sendData);
			serialReceiveData.clear();
			process_flag = STEP_READ_DEVICE_INFO;
			break;
		case STEP_READ_DEVICE_INFO:
			//qDebug()<<"STEP_READ_DEVICE_INFO";
			{
				QString info;

				m_time_out_serial->stop();

				info.append(serialReceiveData);
                ui->success_label->setText("数据打包中....");
				dedata->info->cc_domain.append(dedata->gei_info(info,"CC2541 domain: ",": ",0));
				dedata->info->fly900_domain.append(dedata->gei_info(info,"FLY900 domain: ",": ",0));
				dedata->info->imei.append(dedata->gei_info(info,"IMEI: ",": ",0));
				//dedata->info->device_id.append(dedata->gei_info(info,"DevId: ",": ",0));//不重复添加 zhangyh
				dedata->info->BT_MAC.append(dedata->gei_info(info,"BT MAC: ",": ",0));
				dedata->info->fly900_version.append(dedata->gei_info(info,"FLY900 version: ",": ",0));
				dedata->info->cc_version.append(dedata->gei_info(info,"CC2541 version: ",": ",0));

                if(("false" != dedata->info->imei) &&
                    ("false" != dedata->info->cc_domain) &&
                    ("false" != dedata->info->fly900_domain) &&
                    ("false" != dedata->info->BT_MAC) &&
                    ("false" != dedata->info->fly900_version) &&
                    ("false" != dedata->info->cc_version))
				{
					ui->imei_lineEdit->setText(dedata->info->imei);
                    ui->devID_lineEdit->setText(dedata->info->device_id);
				}
				else
				{
					if(!is_first_rev_error)
					{
						is_first_rev_error = true;
						serialReceiveData.clear();
						//初始化数据
						dedata->info->BT_MAC.clear();
						dedata->info->cc_domain.clear();
						dedata->info->cc_version.clear();
						//dedata->info->cusid.clear();
						dedata->info->device_id.clear();
						dedata->info->fly900_domain.clear();
						dedata->info->fly900_version.clear();
						dedata->info->imei.clear();
						break;
					}
					else
					{
						stop_process();
                        mysqlClient->mysqlSetusedzero(dedata->info->device_id);
						QMessageBox::warning(this, QStringLiteral("警告"),
												   QStringLiteral("配置信息读取错误"),
												   QMessageBox::Ok) ;
						ui->success_label->setText("配置信息读取错误");
						break;
					}
				}

				process_flag = STEP_PACKET_DATA;
                ui->success_label->setText("上传数据中....");
                on_opensql_mysqlClient();
				if(mysqlClient->mysqlSetOneData(dedata->info))
				{
					m_time_out_serial->stop();
                    ui->success_label->setText("重置密码....");
					sendData.append(endata->packet_commond(AT_DEVICEINFO,"ii",2,19,1));
					serial->write(sendData);
					m_time_out_serial->start();
					process_flag = STEP_INIT_DEVICE_PW;
				}
				else
				{
					stop_process();
				}
				serialReceiveData.clear();
				break;
			}
		case STEP_INIT_DEVICE_PW:
        {
            //qDebug()<<"STEP_INIT_DEVICE_PW";
            m_time_out_serial->stop();
            ui->success_label->setText(tr("<font color=green><b>写号成功</b></font>"));
            if(!IsShow)
            {
                showresult_cusid();
                IsShow = true;
            }
            serialReceiveData.clear();
            if(ui->checkBox_2->isChecked())
            {
                ui->success_label->setText("配置IP中....");
                QString configIp = "AT+TRACERSET=2," + ui->configIp_lineEdit->text() + "\r\n";
                sendData.append(configIp);
                serial->write(sendData);
                sendData.clear();
                ui->success_label->setText("验证IP中....");
                Delay(1000);
                configIp = "AT+TRACERGET=2\r\n";
                sendData.append(configIp);
                serial->write(sendData);
                Delay(1000);
//                m_time_out_serial->start();
                process_flag = STEP_Cnfgur_Ip;
            }
            else
            {
                ui->success_label->setText(tr("<font size=30 color=green><b>PASS</b></font>"));
                stop_process();
                process_flag = STEP_MAX;
            }
            break;
        }
        case STEP_Cnfgur_Ip:
        {
            m_time_out_serial->stop();
            if(serialReceiveData.contains("SEEVER:"))
            {
                QString info;
                info.append(serialReceiveData);
                int index = info.indexOf("SEEVER:");
                info = info.mid(index+7);
                index = info.indexOf("\r\n");
                info = info.mid(0,index);
                info = "\"" + info.replace(",","\",");
                if(ui->configIp_lineEdit->text() == info)
                {
                    ui->success_label->setText(tr("<font color=green><b>配置IP成功</b></font>"));
                    Delay(500);
                    ui->success_label->setText(tr("<font size=30 color=green><b>PASS</b></font>"));
                }
                else
                {
                    QMessageBox::warning(this, QStringLiteral("警告"),
                                               QStringLiteral("配置IP失败"),
                                               QMessageBox::Ok) ;
                    ui->success_label->setText("配置IP失败");
                }
            }
            else
            {
                if(chrgDtctntms--)
                {
                    process_flag = STEP_Cnfgur_Ip;
                    break;
                }
                QMessageBox::warning(this, QStringLiteral("警告"),
                                           QStringLiteral("配置IP失败"),
                                           QMessageBox::Ok) ;
                ui->success_label->setText("配置IP失败");
            }
            stop_process();
            process_flag = STEP_MAX;
            break;
        }
		default:
			serialReceiveData.clear();
			break;
	}
}

void MainWindow::read_settings()
{
	QSettings *readConfig = new QSettings("Option.ini", QSettings::IniFormat);

	QString serial_num = readConfig->value("/serialPort/serial_num").toString();
	quint8 baudRate = readConfig->value("/serialPort/BaudRate").toInt();
	/*QString IP = readConfig->value("/mysql/IP").toString();
				QString IP_PN = readConfig->value("/mysql/IP_PN").toString();
				QString database = readConfig->value("/mysql/database").toString();
				QString table = readConfig->value("/mysql/table").toString();*/
	strpass pass;
	QString IP = pass.getXorEncryptDecrypt(readConfig->value("/mysql/IP").toString(), 11);
	QString IP_PN = pass.getXorEncryptDecrypt(readConfig->value("/mysql/IP_PN").toString(), 12);
	QString database = pass.getXorEncryptDecrypt(readConfig->value("/mysql/database").toString(), 13);
	QString table = pass.getXorEncryptDecrypt(readConfig->value("/mysql/table").toString(), 14);
    QString version = pass.getXorEncryptDecrypt(readConfig->value("/info/FLY900 version").toString(), 15);
    QString mcuversion = pass.getXorEncryptDecrypt(readConfig->value("/info/CC2541 version").toString(), 16);
    QString ConfigIP = pass.getXorEncryptDecrypt(readConfig->value("/info/IP").toString(), 15);
    QString Setdigit = pass.getXorEncryptDecrypt(readConfig->value("/info/Setdigit").toString(), 2);

    int c_checked = readConfig->value("/info/SlrEnrgyCnfg").toInt();
    ui->checkBox->setChecked(c_checked);
    c_checked = readConfig->value("/info/CnfgrngIp").toInt();
    ui->checkBox_2->setChecked(c_checked);

	ui->com_comboBox->setCurrentText(serial_num);
	ui->baud_comboBox->setCurrentIndex(baudRate);
	ui->IP_lineEdit->setText(IP);
	ui->port_lineEdit->setText(IP_PN);
	ui->sql_lineEdit->setText(database);
	ui->table_lineEdit->setText(table);
    ui->Setdigit_lineEdit->setText(Setdigit);
	ui->version_lineEdit->setText(version);
    ui->mcuversion_lineEdit->setText(mcuversion);
    ui->configIp_lineEdit->setText(ConfigIP);
	delete readConfig;
}

void MainWindow::serialReadData()
{
	QByteArray temp = serial->readAll();
#ifdef WIN32//解决中文显示问题
	QTextCodec *codec = QTextCodec::codecForName("GB18030");
	QString buf = codec->toUnicode(temp);
#else
	QString buf = temp;
#endif
	//qDebug()<<"**************"<<temp;
	if(process_flag == STEP_MAX)
	{
		serialReceiveData.clear();
	}
	//qDebug()<<"%%%%%%%%"<<temp;
	if(!temp.isEmpty())
	{
		serialReceiveData.append(temp);
		if(dedata->is_receive_complete(serialReceiveData))
		{
			//qDebug()<<"parse_receive_data";
			//qDebug()<<"serialReadData|"<<serialReceiveData<<"|serialReadData";
            //接收完整 处理
            writelog->setValue("/info/Receive：",temp);
            if(m_message_box->isVisible() && process_flag == STEP_SlrChrgDtcton_ENGINEER) return;

			parse_receive_data();
		}
	}
}

void MainWindow::serial_time_out()
{
	if(m_time_out_serial_count == 7)
	{
		if(m_time_out_serial->isActive())
		{
			stop_process();
			m_time_out_serial->stop();
			m_time_out_serial->setInterval(1000);
			m_time_out_serial_count = 0;
		}
        mysqlClient->mysqlSetusedzero(dedata->info->device_id);
		QMessageBox::warning(this, QStringLiteral("警告"),
								   QStringLiteral("配置超时，请重试"),
								   QMessageBox::Ok) ;

	}
	else
	{
		m_time_out_serial_count++;
	}
}

void MainWindow::on_start_pushButton_clicked()
{
	QByteArray sendData;
	QString user_info;

	if(!serial->isOpen())
	{
		stop_process();
		QMessageBox::warning(this, QStringLiteral("警告"),
								   QStringLiteral("请先打开串口"),
								   QMessageBox::Ok) ;
		return ;
	}	//初始化数据
	dedata->info->BT_MAC.clear();
	dedata->info->cc_domain.clear();
	dedata->info->cc_version.clear();
	dedata->info->cusid.clear();
	dedata->info->device_id.clear();
	dedata->info->fly900_domain.clear();
	dedata->info->fly900_version.clear();
	dedata->info->imei.clear();

	user_info.append(dedata->get_user_info(ui->cuscode_lineEdit->text()));
    //重新打开数据库
    on_opensql_mysqlClient();

    if(mysqlClient->checkIsWrite(user_info))
	{
		stop_process();
		QMessageBox::warning(this, QStringLiteral("警告"),
								   QStringLiteral("禁止写入，此设备已写入信息"),
								   QMessageBox::Ok) ;

		return ;
	}
	ui->success_label->setText("获取数据库信息");
    if(!mysqlClient->mysqlGetOneData())
	{
		stop_process();
		QMessageBox::warning(this, QStringLiteral("警告"),
								   QStringLiteral("数据库已用尽,或数据库不可用"),
								   QMessageBox::Ok) ;
		return ;
	}
	dedata->info->device_id = mysqlClient->current_DEVID;

	if(user_info.contains("false"))
	{
		stop_process();
		QMessageBox::warning(this, QStringLiteral("警告"),
								   QStringLiteral("输入信息有误"),
								   QMessageBox::Ok) ;
		return ;
	}
    //增加显示数据库总记录数功能及可用记录数
    int sumDevieId = mysqlClient->getTtlRcrdNmbr()-1;
    QString DevieId = QString::number(sumDevieId, 10);
    ui->label_devieId_sum->setText(DevieId);
    int sumUsDevieId =  1600371000 - mysqlClient->current_DEVID.toInt();
    QString UsDevieId = QString::number(sumUsDevieId, 10);
    ui->label_usabledevieId_sum->setText(UsDevieId);

    dedata->info->cusid = user_info;
    Delay(1000);
//    ui->success_label->setText("开启工程模式....");
    serial->write("AT+TEST=23,2\r\n");//作为触发条件
    ui->start_pushButton->setEnabled(false);
    process_flag = STEP_SlrChrgDtcton_ENGINEER;
    m_time_out_serial->start();
}

void MainWindow::on_openserial_pushButton_clicked()
{
	if(serial->isOpen())
	{
		serialClose();
		ui->serial_sta_label->setText("<font color=black><b>串口已关闭</b></font>");
		ui->openserial_pushButton->setText("打开串口");
	}
	else
	{
		//初始化串口
		if(serialOpen())
		{
			ui->serial_sta_label->setText("<font color=green><b>串口已打开</b></font>");
			ui->openserial_pushButton->setText("关闭串口");
		}
	}
}

void MainWindow::on_opensql_pushButton_clicked()
{
	if(mysqlClient->mysql_isOpend())
	{
		mysqlClient->mysqlClose();
		ui->sql_sta_label->setText("<font color=black><b>数据库关闭</b></font>");
		ui->opensql_pushButton->setText("打开数据库");
	}
	else
	{
		if(mysqlClient->mysqlInit(ui->IP_lineEdit->text(),ui->port_lineEdit->text(),ui->sql_lineEdit->text()))
		{
			if(mysqlClient->mysqlChangeTable(ui->table_lineEdit->text()) > 0)
			{
				ui->sql_sta_label->setText("<font color=green><b>数据库开启</b></font>");
				ui->opensql_pushButton->setText("关闭数据库");
			}
            else
			{
				QMessageBox::warning(this, QStringLiteral("警告"),
										   QStringLiteral("当前表不可用"),
										   QMessageBox::Ok) ;
			}
		}
		else
		{
			QMessageBox::warning(this, QStringLiteral("警告"),
									   QStringLiteral("数据库打开失败"),
									   QMessageBox::Ok) ;
		}
	}
}

void MainWindow::on_cuscode_lineEdit_textChanged(const QString &arg1)
{
	//if(arg1.contains('\n'))
    if(arg1.length() >= ui->Setdigit_lineEdit->text().toInt())
	{
		ui->cuscode_lineEdit->setEnabled(false);
        IsShow = false;
		on_start_pushButton_clicked();
    }
}

bool MainWindow::on_judgeSnsql_mysqlMzClient(QString snInfo)
{
    if(!mysqlMzClient->mysql_isOpend())
    {
        if(!mysqlMzClient->mysqlInit("139.159.0.202","3306","FLY900H"))
        {
            QMessageBox::warning(this, QStringLiteral("警告"),
                                       QStringLiteral("模组测试对应数据库打开失败"),
                                       QMessageBox::Ok) ;
            return false;
        }
    }
    if(mysqlMzClient->mysqlChangeTable("vLock4_cit_20170831_module") > 0)
    {
        //检测是否通过模组测试
        writelog->setValue("/info/snInfo2",snInfo);
        if(mysqlMzClient->checkAllflagIsTrue(snInfo))
        {
            mysqlMzClient->mysqlClose();
            return true;
        }
        else
        {
            QMessageBox::warning(this, QStringLiteral("警告"),
                                       QStringLiteral("该设备未全部通过模组测试所选检测项"),
                                       QMessageBox::Ok) ;
            return false;
        }
    }
    else
    {
        QMessageBox::warning(this, QStringLiteral("警告"),
                                   QStringLiteral("模组测试对应数据库表不可用"),
                                   QMessageBox::Ok) ;
        return false;
    }
    return false;
}

void MainWindow::on_opensql_mysqlClient()
{
    if(!mysqlClient->mysql_isOpend())
    {
        if(mysqlClient->mysqlInit(ui->IP_lineEdit->text(),ui->port_lineEdit->text(),ui->sql_lineEdit->text()))
        {
            if(!mysqlClient->mysqlChangeTable(ui->table_lineEdit->text()) > 0)
            {
                QMessageBox::warning(this, QStringLiteral("警告"),
                                           QStringLiteral("写号当前表不可用"),
                                           QMessageBox::Ok) ;
            }
        }
        else
        {
            QMessageBox::warning(this, QStringLiteral("警告"),
                                       QStringLiteral("写号数据库打开失败"),
                                       QMessageBox::Ok) ;
        }
    }
}




